﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WakeOnLan
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            byte[] mac = GetMac();

            SendWakeOnLanPacket(mac);
        }

        private static void SendWakeOnLanPacket(byte[] mac)
        {
            //
            // WOL 包通过 UDP 255.255.255.0:40000 发送。
            //
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 40000);

            //
            // WOL 包含了6个字节的属部和16倍6字节序列包含MAC地址.
            //
            byte[] packet = new byte[17 * 6];

            //
            // 尾部6倍的 0xFF.
            //
            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;

            //
            // 魔术包主体部分包含了16倍的MAC地址。
            //
            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];

            //
            // 发送唤醒包。
            //
            client.Send(packet, packet.Length);
        }

        private byte[] GetMac()
        {
            try
            {
                string macText = MacTextBox.Text;
                string[] macs = macText.Split('-');
                byte[] mac = new byte[6];
                for (int i = 0; i < 6; i++)
                {
                    mac[i] = Convert.ToByte(macs[i], 16);
                }
                return mac;
            }
            catch
            {
                MessageBox.Show("输入有误，请检查您输入的MAC地址格式，例如：70-71-BC-22-AE-3A");
                return new byte[6];
            }
        }

    }
}
